<template>
  <div class="page-container">
    <h1 class="metro-title"><i class="metro-icon"></i>基本查询功能</h1>
    <div id="mapView" class="map-view">
      <!-- 图层控制面板 -->
      <div class="layer-control-panel">
        <el-card class="layer-card">
          <el-collapse v-model="activeCollapse">
            <el-collapse-item title="图层显示控制" name="layers">
              <el-space direction="vertical" alignment="stretch" size="small">
                <el-checkbox
                  v-model="layerVisibility.subwayLine"
                  @change="toggleLayerVisibility('subwayLine')"
                  class="metro-checkbox"
                  >地铁线路</el-checkbox
                >
                <el-checkbox
                  v-model="layerVisibility.subwayStation"
                  @change="toggleLayerVisibility('subwayStation')"
                  class="metro-checkbox"
                  >地铁站点</el-checkbox
                >
              </el-space>
            </el-collapse-item>
            <el-collapse-item title="站点搜索" name="stationSearch">
              <el-space direction="vertical" alignment="stretch" size="small">
                <el-input
                  v-model="stationSearchText"
                  placeholder="请输入站点名称关键词"
                  clearable
                  class="metro-input"
                >
                  <template #append>
                    <el-button @click="searchStationByName" class="search-button">
                      <el-icon><Search /></el-icon>
                    </el-button>
                  </template>
                </el-input>
              </el-space>
            </el-collapse-item>
            <el-collapse-item title="线路筛选" name="lineFilter">
              <el-space direction="vertical" alignment="stretch" size="small">
                <el-select
                  v-model="selectedLine"
                  placeholder="请选择地铁线路"
                  clearable
                  @change="filterStationsByLine"
                  class="metro-select"
                >
                  <el-option
                    v-for="line in subwayLines"
                    :key="line.attributes.OBJECTID"
                    :label="line.attributes.LineName"
                    :value="line.attributes.LineName"
                  ></el-option>
                </el-select>
              </el-space>
            </el-collapse-item>

          </el-collapse>
        </el-card>
      </div>

      <!-- 站点属性查看对话框 -->
      <el-dialog
        v-model="stationInfoVisible"
        title="地铁站点信息"
        width="500px"
        :key="stationRefreshKey"
      >
        <div v-if="selectedStation">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="站点名称">{{
              selectedStation.attributes.StationName
            }}</el-descriptions-item>
            <el-descriptions-item label="运营状态">{{
              selectedStation.attributes.Status
            }}</el-descriptions-item>
            <el-descriptions-item label="详细地址">{{
              selectedStation.attributes.Address
            }}</el-descriptions-item>
            <el-descriptions-item label="站点类型">{{
              selectedStation.attributes.StationType
            }}</el-descriptions-item>
            <el-descriptions-item label="换乘路线">{{
              selectedStation.attributes.TransferLines
            }}</el-descriptions-item>
            <el-descriptions-item label="出口数量">{{
              selectedStation.attributes.ExitCount
            }}</el-descriptions-item>
            <el-descriptions-item label="无障碍设施">{{
              selectedStation.attributes.IsDisabledAccess === 'true' ? '有' : '无'
            }}</el-descriptions-item>
            <el-descriptions-item label="日均客流量">{{
              selectedStation.attributes.DailyPassengers
            }}</el-descriptions-item>
            <el-descriptions-item label="高峰时段">{{
              selectedStation.attributes.PeakHour
            }}</el-descriptions-item>
          </el-descriptions>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button type="primary" @click="analyzeNearbySurroundingFacilities" :loading="facilityAnalysisLoading">
              <el-icon><DataAnalysis /></el-icon> 分析周边配套设施
            </el-button>
            <el-button @click="stationInfoVisible = false">关闭</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 线路属性查看对话框 -->
      <el-dialog v-model="lineInfoVisible" title="地铁线路信息" width="500px" :key="lineRefreshKey">
        <div v-if="selectedSubwayLine">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="线路名称">{{
              selectedSubwayLine.attributes.LineName
            }}</el-descriptions-item>
            <el-descriptions-item label="线路编号">{{
              selectedSubwayLine.attributes.LineNumber
            }}</el-descriptions-item>
            <el-descriptions-item label="站点数量">{{
              selectedSubwayLine.attributes.StationCount
            }}</el-descriptions-item>
            <el-descriptions-item label="首班车时间">{{
              selectedSubwayLine.attributes.FirstTrainTime
            }}</el-descriptions-item>
            <el-descriptions-item label="末班车时间">{{
              selectedSubwayLine.attributes.LastTrainTime
            }}</el-descriptions-item>
            <el-descriptions-item label="轨道类型">{{
              selectedSubwayLine.attributes.TrackType
            }}</el-descriptions-item>
            <el-descriptions-item label="日均客流量">{{
              selectedSubwayLine.attributes.DailyPassengers
            }}</el-descriptions-item>
          </el-descriptions>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button type="primary" @click="showLineStations">查看线路站点</el-button>
            <el-button @click="lineInfoVisible = false">关闭</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 搜索结果列表对话框 -->
      <el-dialog
        v-model="searchResultVisible"
        title="站点搜索结果"
        width="500px"
        :key="refreshStationKey"
      >
        <div v-if="searchResults.length > 0">
          <div class="station-list">
            <div
              v-for="(item, index) in searchResults"
              :key="index"
              class="station-item"
              @click="handleStationRowClick(item)"
            >
              <div class="station-info">
                <div class="station-name">{{ item.attributes.StationName || '未知' }}</div>
                <div class="station-address">地址：{{ item.attributes.Address || '未知' }}</div>
                <div class="station-transfer">
                  换乘：{{ item.attributes.TransferLines || '无' }}
                </div>
              </div>
            </div>
          </div>
        </div>
        <div v-else>
          <el-empty description="未找到匹配的站点"></el-empty>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="searchResultVisible = false">关闭</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 线路站点列表对话框 -->
      <el-dialog
        v-model="lineStationsVisible"
        title="线路站点列表"
        width="500px"
        :key="lineStationsKey"
      >
        <div v-if="lineStations.length > 0">
          <h3>{{ selectedSubwayLine?.attributes.LineName || '当前线路' }}的站点</h3>
          <div class="line-stations-list">
            <div
              v-for="(item, index) in lineStations"
              :key="index"
              class="line-station-item"
              @click="viewStationDetail(item)"
            >
              <div class="line-station-info">
                <div class="line-station-name">{{ item.attributes.StationName || '未知' }}</div>
                <div class="line-station-status">状态：{{ item.attributes.Status || '未知' }}</div>
                <div class="line-station-transfer">
                  换乘：{{ item.attributes.TransferLines || '无' }}
                </div>
              </div>
            </div>
          </div>
        </div>
        <div v-else>
          <el-empty description="未找到该线路的站点"></el-empty>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="lineStationsVisible = false">关闭</el-button>
          </span>
        </template>
      </el-dialog>


      <!-- 周边配套设施完善度分析结果对话框 -->
      <el-dialog
        v-model="facilityAnalysisVisible"
        :title="`${selectedStation?.attributes.StationName || '当前站点'}周边配套设施完善度分析`"
        width="800px"
        destroy-on-close
        @closed="clearChartDescription"
      >
        <div v-if="facilityAnalysisLoading" class="analysis-loading">
          <el-skeleton :rows="10" animated />
        </div>
        <div v-else-if="facilityAnalysisData">
          <div class="facility-analysis-container">
            <!-- 配套设施完善度总体评分 -->
            <div class="facility-score-section">
              <h3>配套设施完善度评分</h3>
              <div class="score-container">
                <el-progress
                  type="dashboard"
                  :percentage="facilityAnalysisData.overallScore"
                  :color="facilityScoreColor"
                  :stroke-width="10"
                >
                  <template #default>
                    <div class="score-value">{{ facilityAnalysisData.overallScore }}<span class="score-unit">分</span></div>
                    <div class="score-level">{{ facilityAnalysisData.developmentLevel }}</div>
                  </template>
                </el-progress>
              </div>
              <div class="score-summary">
                <p>{{ facilityAnalysisData.summary }}</p>
              </div>
            </div>

            <!-- 各类设施分布 -->
            <div class="facility-distribution-section">
              <h3>周边设施分布</h3>
              <div class="chart-container" ref="facilityChartContainer"></div>
              <div class="facility-analysis">
                <p>{{ facilityAnalysisData.facilityAnalysis }}</p>
              </div>
            </div>

            <!-- 配套设施指标详情 -->
            <div class="facility-indicators-section">
              <h3>配套设施指标详情</h3>
              <el-table :data="facilityAnalysisData.indicators" stripe style="width: 100%">
                <el-table-column prop="name" label="指标名称" width="180" />
                <el-table-column prop="value" label="数值" width="120" />
                <el-table-column prop="description" label="说明" />
              </el-table>
            </div>

            <!-- 发展建议 -->
            <div class="development-suggestions-section">
              <h3>发展建议</h3>
              <el-card class="suggestion-card">
                <div v-for="(suggestion, index) in facilityAnalysisData.suggestions" :key="index" class="suggestion-item">
                  <el-icon><InfoFilled /></el-icon>
                  <span>{{ suggestion }}</span>
                </div>
              </el-card>
            </div>
          </div>
        </div>
        <div v-else>
          <el-empty description="暂无配套设施分析数据"></el-empty>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="facilityAnalysisVisible = false">关闭</el-button>
            <el-button type="primary" @click="exportFacilityAnalysis" :disabled="!facilityAnalysisData">
              <el-icon><Download /></el-icon> 导出配套设施分析报告
            </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { nextTick, onMounted, onUnmounted, ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, DataAnalysis, Download, InfoFilled } from '@element-plus/icons-vue'
import Map from '@arcgis/core/Map.js'
import MapView from '@arcgis/core/views/MapView.js'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer.js'
import Graphic from '@arcgis/core/Graphic.js'
import Query from '@arcgis/core/rest/support/Query.js'
import gaodeLayer from '../utils/GaoDeBaseLayer'
import subway from '@/assets/subway.png'
import PictureMarkerSymbol from '@arcgis/core/symbols/PictureMarkerSymbol'
import * as echarts from 'echarts'
import { usePassengerFlowStore } from '../stores/passengerFlow'
import { getSubwayStationSurroundingFacilities, POI_TYPE } from '@/utils/gaodeAPI'

let view: MapView | null = null
let subwayLineLayer: FeatureLayer | null = null
let subwayStationLayer: FeatureLayer | null = null

// 初始化客流量存储
const passengerFlowStore = usePassengerFlowStore()

// 图层可见性控制
const layerVisibility = ref({
  subwayLine: true,
  subwayStation: true,
})

// 控制折叠面板的展开状态
const activeCollapse = ref(['layers', 'stationSearch', 'lineFilter'])
const refreshStationKey = ref(0)
const lineStationsKey = ref(0)

// 查询结果相关
const stationInfoVisible = ref(false)
const lineInfoVisible = ref(false)
const searchResultVisible = ref(false)
const lineStationsVisible = ref(false)
// 添加一个标志变量来表示是否选择了站点
const hasSelectedStation = ref(false)
let selectedStation: Graphic | null = null
let selectedSubwayLine: Graphic | null = null

const lineRefreshKey = ref(0)
const stationRefreshKey = ref(0)

// 周边配套设施分析相关
const facilityAnalysisVisible = ref(false)
const facilityAnalysisLoading = ref(false)
const facilityChartContainer = ref<HTMLElement | null>(null)
let facilityChart: echarts.ECharts | null = null

// 周边配套设施分析数据接口
interface FacilityIndicator {
  name: string
  value: number | string
  description: string
}

interface FacilityAnalysisData {
  overallScore: number
  developmentLevel: string
  summary: string
  facilityAnalysis: string
  facilityDistribution: {
    name: string
    value: number
    percentage: number
  }[]
  indicators: FacilityIndicator[]
  suggestions: string[]
}

const facilityAnalysisData = ref<FacilityAnalysisData | null>(null)

// 根据评分计算颜色
const facilityScoreColor = computed(() => {
  if (!facilityAnalysisData.value) return '#909399'
  const score = facilityAnalysisData.value.overallScore
  if (score >= 80) return '#67C23A' // 高分 - 绿色
  if (score >= 60) return '#E6A23C' // 中分 - 黄色
  return '#F56C6C' // 低分 - 红色
})



// 站点搜索相关
const stationSearchText = ref('')
let searchResults: Graphic[] = []

// 线路筛选相关
const selectedLine = ref('')
let subwayLines: Graphic[] = []
let lineStations: Graphic[] = []

// 切换图层可见性
const toggleLayerVisibility = (layerType: string) => {
  switch (layerType) {
    case 'subwayLine':
      if (subwayLineLayer) {
        subwayLineLayer.visible = Boolean(layerVisibility.value.subwayLine)
      }
      break
    case 'subwayStation':
      if (subwayStationLayer) {
        subwayStationLayer.visible = Boolean(layerVisibility.value.subwayStation)
      }
      break
  }
}

// 搜索站点
const searchStationByName = () => {
  if (!subwayStationLayer) {
    ElMessage.warning('站点图层未加载')
    return
  }

  if (!stationSearchText.value.trim()) {
    ElMessage.warning('请输入搜索关键词')
    return
  }

  // 创建查询对象
  const query = new Query()
  query.where = `StationName LIKE '%${stationSearchText.value}%'`
  query.outFields = ['*']
  query.returnGeometry = true

  // 执行查询
  subwayStationLayer
    .queryFeatures(query)
    .then((results) => {
      nextTick(() => {
        refreshStationKey.value++
      })
      if (results.features && results.features.length > 0) {
        searchResults = results.features
        console.log('查询结果:', searchResults)
        searchResultVisible.value = true
      } else {
        searchResults = []
        searchResultVisible.value = true
        ElMessage.info('未找到匹配的站点')
      }
    })
    .catch((error) => {
      console.error('查询站点出错:', error)
      ElMessage.error('查询站点失败')
    })
}

// 处理搜索结果行点击
const handleStationRowClick = (row: Graphic) => {
  selectedStation = row
  hasSelectedStation.value = true // 设置标志为true
  searchResultVisible.value = false
  stationInfoVisible.value = true

  // 记录站点访问，每次点击增加10个客流量
  passengerFlowStore.recordStationVisit(
    row.attributes.OBJECTID.toString(),
    row.attributes.StationName,
    10
  )

  // 如果有地图视图，则定位到该站点
  if (view && row.geometry) {
    view.goTo({
      target: row.geometry,
      zoom: 15,
    })
  }
}

// 加载地铁线路列表
const loadSubwayLines = () => {
  if (!subwayLineLayer) {
    ElMessage.warning('线路图层未加载')
    return
  }

  // 查询所有线路
  const query = subwayLineLayer.createQuery()
  query.outFields = ['*']
  query.returnGeometry = false

  subwayLineLayer
    .queryFeatures(query)
    .then((results) => {
      if (results.features && results.features.length > 0) {
        subwayLines = results.features
      }
    })
    .catch((error) => {
      console.error('加载线路列表出错:', error)
      ElMessage.error('加载线路列表失败')
    })
}

// 根据线路筛选站点
const filterStationsByLine = () => {
  if (!subwayStationLayer || !selectedLine.value) {
    return
  }

  // 创建查询对象
  const query = new Query()
  query.where = `TransferLines LIKE '%${selectedLine.value}%'`
  query.outFields = ['*']
  query.returnGeometry = true
  console.log(selectedLine.value)
  // 执行查询
  subwayStationLayer
    .queryFeatures(query)
    .then((results) => {
      if (results.features && results.features.length > 0) {
        // 高亮显示筛选出的站点

        if (view) {
          view.goTo(results.features)
        }
      } else {
        ElMessage.info('未找到该线路的站点')
      }
    })
    .catch((error) => {
      console.error('筛选站点出错:', error)
      ElMessage.error('筛选站点失败')
    })
}

// 查看线路站点
const showLineStations = async () => {
  if (!subwayStationLayer || !selectedSubwayLine) {
    ElMessage.warning('站点图层未加载或未选择线路')
    return
  }

  try {
    // 创建查询对象
    const query = new Query()
    query.where = `LineID LIKE '%${selectedSubwayLine.attributes.OBJECTID}%'`
    query.outFields = ['*']
    query.returnGeometry = true

    // 执行查询
    const results = await subwayStationLayer.queryFeatures(query)

    nextTick(() => {
      lineStationsKey.value++
    })

    if (results.features && results.features.length > 0) {
      lineStations = results.features
      lineInfoVisible.value = false
      lineStationsVisible.value = true
    } else {
      lineStations = []
      lineStationsVisible.value = true
      ElMessage.info('该线路上未找到站点')
    }
  } catch (error) {
    console.error('查询线路站点出错:', error)
    ElMessage.error('查询线路站点失败')
  }
}

// 查看站点详情
const viewStationDetail = (station: Graphic) => {
  selectedStation = station
  hasSelectedStation.value = true // 设置标志为true
  lineStationsVisible.value = false
  stationInfoVisible.value = true

  // 记录站点访问，每次点击增加10个客流量
  passengerFlowStore.recordStationVisit(
    station.attributes.OBJECTID.toString(),
    station.attributes.StationName,
    10
  )

  // 如果有地图视图，则定位到该站点
  if (view && station.geometry) {
    view.goTo({
      target: station.geometry,
      zoom: 15,
    })
  }
}



// 初始化地图
onMounted(() => {
  // 创建地铁线路图层
  subwayLineLayer = new FeatureLayer({
    url: 'https://services7.arcgis.com/WAsbhBMtbJ0DBeIA/arcgis/rest/services/地铁站点/FeatureServer/1',
    title: '地铁线路',
    visible: Boolean(layerVisibility.value.subwayLine),
    outFields: ['*'], // 确保所有字段都可用
    popupEnabled: false, // 禁用默认弹出窗口，使用自定义弹窗
  })

  // 创建地铁站点图层
  subwayStationLayer = new FeatureLayer({
    url: 'https://services7.arcgis.com/WAsbhBMtbJ0DBeIA/arcgis/rest/services/地铁站点/FeatureServer/0',
    title: '地铁站点',
    visible: Boolean(layerVisibility.value.subwayStation),
    outFields: ['*'],
    popupEnabled: false,
    renderer: {
        type: 'simple',
        symbol: new PictureMarkerSymbol({
          url: subway,
          width: 24,
          height: 24,
        }),
      },
  })

  // 创建地图实例
  const map = new Map({
    basemap: {
      baseLayers: [gaodeLayer],
    },
    layers: [subwayLineLayer, subwayStationLayer], // 添加图层到地图
  })

  // 创建地图视图
  view = new MapView({
    container: 'mapView',
    map: map,
    zoom: 10,
    center: [116.397428, 39.90923], // 默认中心点（北京）
  })

  // 监听点击事件，用于查询要素信息
  view.on('click', async function (event) {
    // 转换空间参考
    const mapPoint = event.mapPoint
    // 创建查询对象
    const query = new Query()
    query.geometry = mapPoint
    query.distance = 0.5 // 增加点击容差
    query.units = 'kilometers'
    query.spatialRelationship = 'intersects'
    query.returnGeometry = true
    query.outFields = ['*']

    try {
      // 查询地铁线路图层
      if (subwayLineLayer && subwayLineLayer.visible) {
        const lineResult = await subwayLineLayer.queryFeatures(query)
        if (lineResult.features.length > 0) {
          // 找到线路，显示信息
          selectedSubwayLine = lineResult.features[0]
          lineInfoVisible.value = true
          nextTick(() => {
            lineRefreshKey.value++
          })
          return
        }
      }

      // 查询地铁站点图层
      if (subwayStationLayer && subwayStationLayer.visible) {
        const stationResult = await subwayStationLayer.queryFeatures(query)
        if (stationResult.features.length > 0) {
          // 找到站点，显示信息
          selectedStation = stationResult.features[0]
          hasSelectedStation.value = true // 设置标志为true
          stationInfoVisible.value = true

          // 记录站点访问，每次点击增加10个客流量
          passengerFlowStore.recordStationVisit(
            selectedStation.attributes.OBJECTID.toString(),
            selectedStation.attributes.StationName,
            10
          )

          nextTick(() => {
            stationRefreshKey.value++
          })
          return
        }
      }
    } catch (error) {
      console.error('查询要素出错:', error)
      ElMessage.error('查询要素失败')
    }
  })

  // 加载地铁线路列表
  loadSubwayLines()
})

// 分析周边配套设施完善度
const analyzeNearbySurroundingFacilities = async () => {
  if (!selectedStation) {
    ElMessage.warning('请先选择一个地铁站点')
    return
  }

  try {
    facilityAnalysisLoading.value = true
    facilityAnalysisVisible.value = true

    // 获取站点坐标
    const geometry = selectedStation.geometry as any
    const longitude = geometry.longitude || geometry.x
    const latitude = geometry.latitude || geometry.y

    // 查询各类型设施（减少类型数量，避免超出API限制）
    const facilityTypes = [
      { type: POI_TYPE.RESTAURANT, name: '餐饮' },
      { type: POI_TYPE.SHOPPING, name: '购物' },
      { type: POI_TYPE.LIFE_SERVICE, name: '生活服务' },
      { type: POI_TYPE.ENTERTAINMENT, name: '休闲娱乐' },
      { type: POI_TYPE.BUSINESS, name: '商务' },
    ]

    // 串行查询所有设施类型，避免超出API并发限制
    const facilitiesResults = []
    for (const { type } of facilityTypes) {
      try {
        // 添加延迟，避免请求过于频繁
        if (facilitiesResults.length > 0) {
          await new Promise(resolve => setTimeout(resolve, 300))
        }
        const result = await getSubwayStationSurroundingFacilities(longitude, latitude, type, 1000)
        facilitiesResults.push(result)
      } catch (error) {
        console.error(`查询设施类型 ${type} 失败:`, error)
        // 如果查询失败，添加空数组作为结果，避免中断整个分析过程
        facilitiesResults.push([])
      }
    }

    // 处理查询结果 - 根据typecode分类统计
    // 首先创建一个对象，用于存储每个设施类型的数量
    const typeCodeCounts = {}

    // 遍历所有查询结果，按typecode分类统计
    facilitiesResults.forEach((poiItems, index) => {
      const facilityName = facilityTypes[index].name

      // 统计每个typecode的数量
      poiItems.forEach(poi => {
        // 确保poi.typecode存在
        if (poi.typecode) {
          // 一个POI可能有多个typecode（用|分隔）
          const typecodes = poi.typecode.split('|')
          typecodes.forEach(code => {
            // 获取主类别（前3位）
            const mainType = code.substring(0, 3)
            const key = `${mainType}-${facilityName}`

            if (!typeCodeCounts[key]) {
              typeCodeCounts[key] = 0
            }
            typeCodeCounts[key] += 1
          })
        }
      })
    })

    // 转换为facilityDistribution格式
    const facilityDistribution = Object.entries(typeCodeCounts).map(([key, count]) => {
      const [_, name] = key.split('-')
      return {
        name,
        value: count,
        percentage: 0, // 将在下面计算
        typecode: key.split('-')[0]
      }
    })

    // 合并相同名称的设施类型
    const mergedDistribution = []
    const nameMap = {}

    facilityDistribution.forEach(item => {
      if (nameMap[item.name] !== undefined) {
        const index = nameMap[item.name]
        mergedDistribution[index].value += item.value
      } else {
        nameMap[item.name] = mergedDistribution.length
        mergedDistribution.push({...item})
      }
    })

    // 计算总数和百分比
    const totalFacilities = mergedDistribution.reduce((sum, item) => sum + item.value, 0)
    mergedDistribution.forEach(item => {
      item.percentage = totalFacilities > 0 ? Math.round((item.value / totalFacilities) * 100) : 0
    })

    // 计算经济发展指标
    const businessDensity = calculateBusinessDensity(mergedDistribution)
    const diversityIndex = calculateDiversityIndex(mergedDistribution)
    const commercialPotential = calculateCommercialPotential(mergedDistribution, selectedStation)

    // 计算总体评分 (0-100)
    const overallScore = Math.round((businessDensity * 0.4 + diversityIndex * 0.3 + commercialPotential * 0.3) * 100)

    // 确定配套设施完善度水平
    let developmentLevel = '配套不足'
    if (overallScore >= 80) {
      developmentLevel = '配套完善'
    } else if (overallScore >= 60) {
      developmentLevel = '配套一般'
    }

    // 生成分析摘要
    const summary = generateEconomicSummary(
      selectedStation.attributes.StationName,
      overallScore,
      developmentLevel,
      mergedDistribution
    )

    // 生成设施分析
    const facilityAnalysis = generateFacilityAnalysis(mergedDistribution)

    // 生成发展建议
    const suggestions = generateDevelopmentSuggestions(mergedDistribution, overallScore)

    // 构建配套设施指标详情
    const indicators: FacilityIndicator[] = [
      {
        name: '设施密度指数',
        value: (businessDensity * 100).toFixed(1),
        description: '反映区域内配套设施的密集程度，数值越高表示配套越完善'
      },
      {
        name: '设施多样性指数',
        value: (diversityIndex * 100).toFixed(1),
        description: '反映区域内设施类型的多样化程度，数值越高表示配套类型越丰富'
      },
      {
        name: '配套完善度指数',
        value: (commercialPotential * 100).toFixed(1),
        description: '基于客流量和周边设施综合评估的配套设施完善程度'
      },
      {
        name: '设施总数',
        value: totalFacilities,
        description: '站点1公里范围内的各类设施总数'
      },
      {
        name: '主导设施类型',
        value: getLeadingFacilityType(facilityDistribution),
        description: '在该区域占比最高的设施类型'
      }
    ]

    // 更新分析数据
    facilityAnalysisData.value = {
      overallScore,
      developmentLevel,
      summary,
      facilityAnalysis,
      facilityDistribution: mergedDistribution,
      indicators,
      suggestions
    }

    // 渲染图表
    nextTick(() => {
      renderFacilityDistributionChart()
    })

  } catch (error) {
    console.error('分析经济发展出错:', error)
    ElMessage.error('分析经济发展失败')
  } finally {
    facilityAnalysisLoading.value = false
  }
}

// 计算商业密度指数 (0-1)
const calculateBusinessDensity = (facilityDistribution: any[]) => {
  // 计算商业相关设施数量（餐饮、购物、生活服务、商务）
  const businessFacilities = facilityDistribution
    .filter(item => ['餐饮', '购物', '生活服务', '商务'].includes(item.name))
    .reduce((sum, item) => sum + item.value, 0)

  // 基于经验值，假设1公里范围内有100个以上商业设施为满分
  const maxBusinessFacilities = 100
  return Math.min(businessFacilities / maxBusinessFacilities, 1)
}

// 计算业态多样性指数 (0-1)
const calculateDiversityIndex = (facilityDistribution: any[]) => {
  // 计算有效业态数量（至少有1个设施的类型）
  const effectiveTypes = facilityDistribution.filter(item => item.value > 0).length

  // 计算业态分布均衡度
  const totalFacilities = facilityDistribution.reduce((sum, item) => sum + item.value, 0)
  if (totalFacilities === 0) return 0

  // 计算香农熵 (Shannon Entropy) 作为多样性指标
  let entropy = 0
  facilityDistribution.forEach(item => {
    if (item.value > 0) {
      const p = item.value / totalFacilities
      entropy -= p * Math.log(p)
    }
  })

  // 归一化熵值 (最大熵为ln(n)，其中n为类型数)
  const maxEntropy = Math.log(facilityDistribution.length)
  const normalizedEntropy = maxEntropy > 0 ? entropy / maxEntropy : 0

  // 综合考虑类型数量和分布均衡度
  return (effectiveTypes / facilityDistribution.length) * 0.4 + normalizedEntropy * 0.6
}

// 计算商业潜力指数 (0-1)
const calculateCommercialPotential = (facilityDistribution: any[], station: any) => {
  // 基于客流量评估基础潜力
  const dailyPassengers = parseInt(station.attributes.DailyPassengers) || 0
  const passengerScore = Math.min(dailyPassengers / 50000, 1) // 假设日均5万人次为满分

  // 评估商业互补性 (不同类型设施的协同效应)
  const hasRestaurant = facilityDistribution.find(item => item.name === '餐饮')?.value > 5
  const hasShopping = facilityDistribution.find(item => item.name === '购物')?.value > 5
  const hasEntertainment = facilityDistribution.find(item => item.name === '休闲娱乐')?.value > 3
  const hasLifeService = facilityDistribution.find(item => item.name === '生活服务')?.value > 4
  const hasBusiness = facilityDistribution.find(item => item.name === '商务')?.value > 2

  // 计算协同分数
  let synergyScore = 0
  if (hasRestaurant) synergyScore += 0.2
  if (hasShopping) synergyScore += 0.2
  if (hasEntertainment) synergyScore += 0.2
  if (hasLifeService) synergyScore += 0.2
  if (hasBusiness) synergyScore += 0.2

  // 综合评分
  return passengerScore * 0.6 + synergyScore * 0.4
}

// 获取主导设施类型
const getLeadingFacilityType = (facilityDistribution: any[]) => {
  if (facilityDistribution.length === 0) return '无'

  // 找出数量最多的设施类型
  const leadingType = facilityDistribution.reduce((max, item) =>
    item.value > max.value ? item : max, facilityDistribution[0])

  return leadingType.name
}

// 生成周边配套设施完善度摘要
const generateEconomicSummary = (stationName: string, score: number, level: string, distribution: any[]) => {
  const totalFacilities = distribution.reduce((sum, item) => sum + item.value, 0)
  const leadingType = getLeadingFacilityType(distribution)

  let summary = `${stationName}站点周边配套设施完善度为${level}，综合评分${score}分。`

  if (score >= 80) {
    summary += `该区域配套设施丰富，共有各类设施${totalFacilities}个，以${leadingType}为主，配套设施完善，能够满足居民多样化需求。`
  } else if (score >= 60) {
    summary += `该区域配套设施较为均衡，共有各类设施${totalFacilities}个，以${leadingType}为主，但部分类型设施仍有完善空间。`
  } else {
    summary += `该区域配套设施相对不足，共有各类设施${totalFacilities}个，以${leadingType}为主，配套设施不够完善，有较大的提升空间。`
  }

  return summary
}

// 生成设施分析
const generateFacilityAnalysis = (distribution: any[]) => {
  // 过滤掉数量为0的设施
  const validDistribution = distribution.filter(item => item.value > 0)

  // 如果没有有效数据，返回默认文本
  if (validDistribution.length === 0) {
    return '该站点周边暂无查询到相关设施数据。'
  }

  // 按数量排序
  const sortedDistribution = [...validDistribution].sort((a, b) => b.value - a.value)

  // 分析主要设施类型（取前3个或全部，如果不足3个）
  const topCount = Math.min(sortedDistribution.length, 3)
  const topTypes = sortedDistribution.slice(0, topCount)

  // 找出数量较少的设施类型（数量小于平均值的一半）
  const avgValue = validDistribution.reduce((sum, item) => sum + item.value, 0) / validDistribution.length
  const bottomTypes = validDistribution.filter(item => item.value < avgValue / 2)

  // 生成格式化的分析文本
  let analysis = '该站点周边主要设施类型分布情况：\n\n'

  // 添加详细列表，使用格式化的文本
  validDistribution.forEach(item => {
    analysis += `• ${item.name}: ${item.value}个 (${item.percentage}%)\n`
  })

  // 添加总结
  analysis += '\n'
  if (topTypes.length > 0) {
    analysis += `该站点周边主要设施类型为${topTypes.map(item => item.name).join('、')}，`
    analysis += `分别占比${topTypes.map(item => item.percentage + '%').join('、')}。`
  }

  if (bottomTypes.length > 0) {
    analysis += `而${bottomTypes.map(item => item.name).join('、')}等设施相对较少，`
    analysis += `这表明该区域在这些方面的配套有待完善。`
  }

  return analysis
}

// 生成发展建议
const generateDevelopmentSuggestions = (distribution: any[], score: number) => {
  const suggestions: string[] = []

  // 找出数量少的设施类型
  const weakTypes = distribution.filter(item => item.value < 5)

  if (score < 60) {
    suggestions.push('整体配套设施不足，建议引入更多多元化设施，提高区域生活便利性。')
  }

  if (weakTypes.length > 0) {
    suggestions.push(`加强${weakTypes.map(item => item.name).join('、')}等设施的引入，平衡设施结构，提高配套多样性。`)
  }

  // 根据主导设施类型给出建议
  const leadingType = getLeadingFacilityType(distribution)
  if (leadingType === '餐饮') {
    suggestions.push('当前区域餐饮设施较多，建议进一步提升餐饮多样性，引入不同类型的餐饮选择，满足居民多样化需求。')
  } else if (leadingType === '购物') {
    suggestions.push('购物设施较为集中，建议增加其他生活服务设施，如休闲娱乐、教育培训等，提升区域生活便利性。')
  } else if (leadingType === '商务') {
    suggestions.push('商务设施集中，建议增加生活配套服务设施，如餐饮、便利店、健身场所等，满足周边居民和工作人群需求。')
  }

  // 通用建议
  suggestions.push('结合站点周边居民需求，优化配套设施布局，提高设施的实用性和可达性。')

  return suggestions
}

// 渲染设施分布图表
const renderFacilityDistributionChart = () => {
  if (!facilityChartContainer.value || !facilityAnalysisData.value) return

  // 销毁旧图表
  if (facilityChart) {
    facilityChart.dispose()
  }

  // 初始化图表
  facilityChart = echarts.init(facilityChartContainer.value)

  // 准备数据
  const { facilityDistribution } = facilityAnalysisData.value

  // 过滤掉数量为0的设施类型
  const validDistribution = facilityDistribution.filter(item => item.value > 0)

  // 使用实际数量作为图表值，确保比例正确
  const chartData = validDistribution.map(item => ({
    value: item.value,
    name: `${item.name} (${item.percentage}%)`
  }))

  // 设置图表选项
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      data: chartData.map(item => item.name)
    },
    series: [
      {
        name: '设施分布',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          formatter: '{b}',
          fontSize: 12
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '16',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: true,
          length: 10,
          length2: 10
        },
        data: chartData
      }
    ]
  }

  // 在图表下方添加说明文本
  nextTick(() => {
    if (facilityChartContainer.value && chartData.length > 0) {
      // 清除旧的描述
      const oldDescriptions = facilityChartContainer.value.querySelectorAll('.chart-description')
      oldDescriptions.forEach(el => el.remove())

      // 添加新的描述
      const descriptionDiv = document.createElement('div')
      descriptionDiv.className = 'chart-description'

      facilityChartContainer.value.appendChild(descriptionDiv)
    }
  })

  // 渲染图表
  facilityChart.setOption(option)
}

// 导出配套设施分析报告
const exportFacilityAnalysis = () => {
  if (!facilityAnalysisData.value) {
    ElMessage.warning('暂无配套设施分析数据可导出')
    return
  }

  // 这里可以实现导出功能，例如生成PDF或Excel
  ElMessage.success('配套设施分析报告导出功能将在后续版本中实现')
}

// 清除图表描述
const clearChartDescription = () => {
  if (facilityChartContainer.value) {
    const descriptionElements = facilityChartContainer.value.querySelectorAll('.chart-description')
    descriptionElements.forEach(element => element.remove())
  }
}

// 创建图表调整函数
const resizeChart = () => {
  if (facilityChart) {
    facilityChart.resize()
  }
}

// 监听窗口大小变化，调整图表大小
window.addEventListener('resize', resizeChart)

// 组件卸载时清理资源
onUnmounted(() => {
  if (view) {
    view = null
  }

  if (facilityChart) {
    facilityChart.dispose()
    facilityChart = null
  }

  // 移除事件监听
  window.removeEventListener('resize', resizeChart)
})

</script>

<style scoped>
.page-container {
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  height: calc(100vh - 140px);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.metro-title {
  margin-bottom: 20px;
  color: #0052cc;
  font-size: 28px;
  font-weight: 600;
  display: flex;
  align-items: center;
  position: relative;
  padding-left: 40px;
  letter-spacing: 1px;
}

.metro-title::before {
  content: '';
  position: absolute;
  left: 0;
  width: 30px;
  height: 30px;
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="%230052cc"><path d="M15.5,5.5c1.1,0,2-0.9,2-2s-0.9-2-2-2s-2,0.9-2,2S14.4,5.5,15.5,5.5z M5,12c-2.8,0-5,2.2-5,5s2.2,5,5,5s5-2.2,5-5S7.8,12,5,12z M5,20.5c-1.9,0-3.5-1.6-3.5-3.5s1.6-3.5,3.5-3.5s3.5,1.6,3.5,3.5S6.9,20.5,5,20.5z M10.8,10.5l2.4-2.4l0.8,0.8c1.3,1.3,3,2.1,5.1,2.1V9.5c-1.5,0-2.7-0.6-3.6-1.5l-1.9-1.9C13.1,5.7,12.6,5.5,12,5.5c-0.6,0-1.1,0.2-1.4,0.6L7,9.5c-0.4,0.4-0.6,0.9-0.6,1.5c0,0.6,0.2,1.1,0.6,1.5L10,15.5v4h2v-5l-2.4-2.4L10.8,10.5z M19,12c-2.8,0-5,2.2-5,5s2.2,5,5,5s5-2.2,5-5S21.8,12,19,12z M19,20.5c-1.9,0-3.5-1.6-3.5-3.5s1.6-3.5,3.5-3.5s3.5,1.6,3.5,3.5S20.9,20.5,19,20.5z"/></svg>');
  background-repeat: no-repeat;
  background-size: contain;
}

.map-view {
  width: 100%;
  height: 100%;
  position: relative;
  flex-grow: 1;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: inset 0 0 10px rgba(0, 0, 0, 0.1);
}

.layer-control-panel {
  position: absolute;
  top: 20px;
  right: 20px;
  z-index: 10;
  width: 280px;
}

.layer-card {
  background-color: rgba(255, 255, 255, 0.92);
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  border: none;
  overflow: hidden;
}

.layer-card :deep(.el-collapse) {
  border: none;
}

.layer-card :deep(.el-collapse-item__header) {
  font-weight: 600;
  color: #0052cc;
  background-color: rgba(240, 245, 255, 0.8);
  padding: 12px 16px;
  border-bottom: 2px solid #e6effd;
}

.layer-card :deep(.el-collapse-item__content) {
  padding: 16px;
}

.metro-checkbox :deep(.el-checkbox__label) {
  font-size: 15px;
  color: #333;
}

.metro-checkbox :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #0052cc;
  border-color: #0052cc;
}

.metro-input :deep(.el-input__inner) {
  border-color: #d0d9e6;
  border-radius: 6px 0 0 6px;
}

.metro-input :deep(.el-input__inner:focus) {
  border-color: #0052cc;
}

.metro-input :deep(.el-input-group__append) {
  padding: 0;
  border-color: #d0d9e6;
}

.search-button {
  background-color: #0052cc;
  color: white;
  border: none;
  border-radius: 0 6px 6px 0;
  padding: 0 15px;
  height: 100%;
}

.search-button:hover {
  background-color: #003d99;
}

.metro-select {
  width: 100%;
}

.metro-select :deep(.el-input__inner) {
  border-color: #d0d9e6;
  border-radius: 6px;
}

.metro-select :deep(.el-input__inner:focus) {
  border-color: #0052cc;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 8px;
}

/* 对话框样式 */
:deep(.el-dialog) {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
}

:deep(.el-dialog__header) {
  background-color: #0052cc;
  color: white;
  padding: 16px 20px;
  margin: 0;
}

:deep(.el-dialog__title) {
  color: white;
  font-weight: 600;
  font-size: 18px;
}

:deep(.el-dialog__body) {
  padding: 24px;
}

:deep(.el-button--primary) {
  background-color: #0052cc;
  border-color: #0052cc;
  font-weight: 600;
}

:deep(.el-button--primary:hover) {
  background-color: #003d99;
  border-color: #003d99;
}

/* 站点列表样式 */
.station-list,
.line-stations-list {
  max-height: 400px;
  overflow-y: auto;
  border-radius: 8px;
  border: 1px solid #e6effd;
}

.station-item,
.line-station-item {
  padding: 16px;
  border-bottom: 1px solid #e6effd;
  cursor: pointer;
  transition: all 0.3s;
}

.station-item:hover,
.line-station-item:hover {
  background-color: #f0f5ff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 82, 204, 0.1);
}

.station-item:last-child,
.line-station-item:last-child {
  border-bottom: none;
}

.station-info,
.line-station-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.station-name,
.line-station-name {
  font-weight: 600;
  color: #0052cc;
  font-size: 16px;
}

.station-address {
  color: #606266;
  display: flex;
  align-items: center;
}

.station-address::before {
  content: '';
  display: inline-block;
  width: 14px;
  height: 14px;
  margin-right: 6px;
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="%23606266"><path d="M12,2C8.13,2,5,5.13,5,9c0,5.25,7,13,7,13s7-7.75,7-13C19,5.13,15.87,2,12,2z M12,11.5c-1.38,0-2.5-1.12-2.5-2.5s1.12-2.5,2.5-2.5s2.5,1.12,2.5,2.5S13.38,11.5,12,11.5z"/></svg>');
  background-repeat: no-repeat;
  background-size: contain;
}

.station-transfer,
.line-station-transfer {
  color: #0052cc;
  font-size: 0.9em;
  display: flex;
  align-items: center;
}

.station-transfer::before,
.line-station-transfer::before {
  content: '';
  display: inline-block;
  width: 14px;
  height: 14px;
  margin-right: 6px;
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="%230052cc"><path d="M17.5,4.5c-1.95,0-4.05,0.4-5.5,1.5c-1.45-1.1-3.55-1.5-5.5-1.5S2.45,4.9,1,6v14.65c0,0.65,0.73,0.45,0.75,0.45C3.1,20.45,5.05,20,6.5,20c1.95,0,4.05,0.4,5.5,1.5c1.35-0.85,3.8-1.5,5.5-1.5c1.65,0,3.35,0.3,4.75,1.05C22.66,21.26,23,20.86,23,20.6V6C21.51,4.88,19.37,4.5,17.5,4.5z M21,18.5c-1.1-0.35-2.3-0.5-3.5-0.5c-1.7,0-4.15,0.65-5.5,1.5V8c1.35-0.85,3.8-1.5,5.5-1.5c1.2,0,2.4,0.15,3.5,0.5V18.5z"/></svg>');
  background-repeat: no-repeat;
  background-size: contain;
}

.line-station-status {
  color: #67c23a;
  font-size: 0.9em;
  display: flex;
  align-items: center;
}

.line-station-status::before {
  content: '';
  display: inline-block;
  width: 14px;
  height: 14px;
  margin-right: 6px;
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="%2367c23a"><path d="M12,2C6.48,2,2,6.48,2,12s4.48,10,10,10s10-4.48,10-10S17.52,2,12,2z M10,17l-5-5l1.41-1.41L10,14.17l7.59-7.59L19,8L10,17z"/></svg>');
  background-repeat: no-repeat;
  background-size: contain;
}

/* 描述列表样式 */
:deep(.el-descriptions) {
  background-color: #f9fbff;
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-descriptions__label) {
  background-color: #f0f5ff;
  font-weight: 500;
  color: #0052cc;
}

:deep(.el-descriptions__content) {
  padding: 12px 16px;
}

/* 周边设施查询样式 */
.facility-search-tip {
  color: #606266;
  font-size: 14px;
  margin-bottom: 8px;
}

.search-radius-slider {
  margin: 12px 0;
}

.facility-search-btn {
  width: 100%;
  margin-top: 8px;
}

.facility-list {
  max-height: 400px;
  overflow-y: auto;
  border-radius: 8px;
  border: 1px solid #e6effd;
}

.facility-item {
  padding: 16px;
  border-bottom: 1px solid #e6effd;
  transition: all 0.3s;
}

.facility-item:hover {
  background-color: #f0f5ff;
}

.facility-item:last-child {
  border-bottom: none;
}

.facility-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.facility-name {
  font-weight: 600;
  color: #0052cc;
  font-size: 16px;
}

.facility-distance {
  color: #67c23a;
  font-size: 14px;
}

.facility-address {
  color: #606266;
  font-size: 14px;
}

.facility-tel {
  color: #409eff;
  font-size: 14px;
}

/* 周边配套设施分析样式 */
.facility-analysis-container {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.facility-score-section,
.facility-distribution-section,
.facility-indicators-section,
.development-suggestions-section {
  background-color: #f9fbff;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.facility-score-section h3,
.facility-distribution-section h3,
.facility-indicators-section h3,
.development-suggestions-section h3 {
  color: #0052cc;
  margin-top: 0;
  margin-bottom: 16px;
  font-size: 18px;
  font-weight: 600;
  border-bottom: 2px solid #e6effd;
  padding-bottom: 8px;
}

.score-container {
  display: flex;
  justify-content: center;
  margin: 20px 0;
}

.score-value {
  font-size: 28px;
  font-weight: bold;
  color: #0052cc;
}

.score-unit {
  font-size: 16px;
  margin-left: 2px;
}

.score-level {
  font-size: 14px;
  color: #606266;
  margin-top: 4px;
}

.score-summary {
  margin-top: 16px;
  color: #333;
  line-height: 1.6;
}

.chart-container {
  height: 350px;
  margin: 16px 0;
  position: relative;
}

.chart-description {
  text-align: left;
  color: #606266;
  font-size: 14px;
  margin-top: 10px;
}

.chart-description p {
  text-align: center;
  margin-bottom: 10px;
  font-weight: 500;
}

.chart-details {
  list-style: none;
  padding: 0;
  margin: 0;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.chart-details li {
  margin: 0;
  padding: 8px 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-details li::before {
  content: '';
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #0052cc;
  margin-right: 8px;
}

.facility-type {
  font-weight: 600;
  color: #0052cc;
}

.facility-info {
  display: flex;
  align-items: center;
}

.facility-stats {
  display: flex;
  align-items: center;
  gap: 5px;
}

.facility-count {
  font-weight: 500;
  color: #333;
}

.facility-percentage {
  color: #67c23a;
  font-size: 14px;
}

.facility-analysis {
  margin-top: 16px;
  color: #333;
  line-height: 1.6;
}

.suggestion-card {
  background-color: #fff;
  border-radius: 8px;
}

.suggestion-item {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  padding: 8px 0;
  border-bottom: 1px dashed #e6effd;
}

.suggestion-item:last-child {
  border-bottom: none;
}

.suggestion-item .el-icon {
  color: #0052cc;
  margin-top: 3px;
}

.analysis-loading {
  padding: 20px;
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .layer-control-panel {
    width: 240px;
    top: 10px;
    right: 10px;
  }

  .metro-title {
    font-size: 24px;
  }

  .chart-container {
    height: 250px;
  }
}
</style>
